package com.perfectbeauties.admin.parser.sites;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import com.perfectbeauties.admin.parser.IParser;
import com.perfectbeauties.admin.parser.ParserUtil;

public class XArtParser implements IParser {

	private static final String URL = "http://www.x-cash.com/affiliate/galleries?PA=2289189";
	
	// Set to -1 or 0 to turn off sampling
	private static final int SAMPLE = -1;
	
	public boolean parse() {
		
		try {
		
			URL url = new URL(URL);
	        URLConnection yc = url.openConnection();
	        BufferedReader in = new BufferedReader(
	                                new InputStreamReader(
	                                yc.getInputStream()));
	        
	        int galleryCount = 0;
	        
	        String line = in.readLine();
	        while (line != null) {
	            while (!line.contains("<div class=\"entrydata\">")) {
	            	line = in.readLine();
	            }
	            
	            line = in.readLine();
	            line = in.readLine();
	            
	            String name = line.substring(line.indexOf("<h4>")+4,line.indexOf("</h4>")).trim();
	            
	            line = in.readLine();
	            
	            String desc = line.substring(line.indexOf("<p>")+3,line.indexOf("</p>")).trim();
	            
	            line = in.readLine();
	            line = in.readLine();
	            line = in.readLine();
	            line = in.readLine();
	            line = in.readLine();
	            line = in.readLine();
	            line = in.readLine();
	            line = in.readLine();
	            line = in.readLine();
	            line = in.readLine();
	            
	            String zip = line.substring(0, line.lastIndexOf(".zip")+4).trim();
	            
	            String result = ParserUtil.submit(name, desc, 1, zip);
	            
	            if (result.equals("Warning:Exists")) {
	            	break;
	            }
	            
				System.out.println(result+" ("+name+")");	
								
				line = in.readLine();
				
				galleryCount++;
				
				if (SAMPLE > 0 && galleryCount >= SAMPLE) {
					break;
				}
	            
	        }
	        in.close();
	        
	        return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
}
